<template>
  <div class="kv-root-wrapper">
    <el-form :disabled="readonly" label-position="top">
      <el-form-item :label="$t('business.workload.annotations')">
        <template #label>
          <div class="w-full flex justify-between">
            <span>{{ $t("business.workload.annotations") }}</span>
            <el-button v-if="create" link type="primary" @click="addAnnotation">
              {{ $t("commons.button.add") }}
            </el-button>
            <el-button
              v-else
              link
              type="primary"
              @click="onShouldEditGroup('annotations')"
            >
              {{ $t("commons.button.edit") }}
            </el-button>
          </div>
        </template>
        <KoKvobjectTable
          :key="uiState.annotationViewKey"
          v-model:model-value="metadata.annotations"
          :readonly="readonly"
          :disabled-keys="[
            InjectLabelKey.AppName,
            PresetAnnotationKey.Alias,
            PresetAnnotationKey.ImagePullSecret
          ]"
          :editable="create"
        />
      </el-form-item>
      <el-form-item :label="$t('business.workload.label')" required>
        <template #label>
          <div class="w-full flex justify-between">
            <span>{{ $t("business.workload.label") }}</span>
            <el-button v-if="create" link type="primary" @click="addLabel()">
              {{ $t("commons.button.add") }}
            </el-button>
            <el-button
              v-else
              link
              type="primary"
              @click="onShouldEditGroup('labels')"
            >
              {{ $t("commons.button.edit") }}
            </el-button>
          </div>
        </template>
        <ko-kvobject-table
          :key="uiState.labelViewKey"
          v-model:model-value="metadata.labels"
          :readonly="readonly"
          :disabled-keys="[InjectLabelKey.AppName]"
          :editable="create"
        />
      </el-form-item>
    </el-form>

    <el-dialog
      v-model="uiState.dialogEditVisible"
      :title="$t('commons.button.edit')"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" label-position="top" style="margin-left: 30px">
        <div v-if="uiState.showOption">
          <el-form-item
            :label="$t('business.workload.edit_option')"
            prop="optionMode"
          >
            <ko-data-item
              v-model="editType"
              itemType="radio"
              radioLayout="vertical"
              :radios="editTypeOptions"
              @change="onEditTypeChange"
            />
            <div v-if="editType === 'batch'">
              <span>
                {{ $t("business.workload.notice") }} spec.selector.matchLabels
                {{ $t("business.workload.recreate_tips") }}
              </span>
            </div>
          </el-form-item>
        </div>
        <table style="width: 100%" class="tab-table">
          <tr v-for="(row, index) in dataList" :key="index">
            <td width="49%">
              <ko-data-item
                v-model="row.key"
                :disabled="disableDialogRowDelete(row)"
                placeholder="e.g. foo"
                clearable
                itemType="input"
              />
            </td>
            <td width="49%">
              <ko-data-item
                v-model="row.value"
                :disabled="disableDialogRowDelete(row)"
                clearable
                itemType="input"
              />
            </td>
            <td width="4%">
              <el-button
                type="text"
                :disabled="disableDialogRowDelete(row)"
                style="font-size: 10px"
                @click="onHandleDeleteRow(dataList, row)"
              >
                {{ $t("commons.button.delete") }}
              </el-button>
            </td>
          </tr>
          <tr>
            <td align="left">
              <el-button @click="onHandleAddRow(dataList)">
                {{ $t("commons.button.add") }}
              </el-button>
            </td>
          </tr>
        </table>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button size="small" @click="uiState.dialogEditVisible = false">
            {{ $t("commons.button.cancel") }}
          </el-button>
          <el-button size="small" @click="syncToModel">
            {{ $t("commons.button.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import koKvobjectTable from "./ko-kvobject-table.vue";
import {
  InjectLabelKey,
  LabelSelector,
  ObjectMeta,
  PresetAnnotationKey
} from "../../../api/k8s";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import {
  mergeListToObject,
  objectToList,
  setObjectFromKeys
} from "../../../utils";
import KoKvobjectTable from "./ko-kvobject-table.vue";

const { t } = useI18n();

type Prop = {
  readonly?: boolean;
  create?: boolean;
};

const props = defineProps<Prop>();
const metadata = defineModel<ObjectMeta>("metadata", { required: true });
const selector = defineModel<LabelSelector>("selector", { required: false });
const editType = defineModel<EditEffectType>("editType", {
  required: false,
  default: "single"
});

type ListRow = {
  key: string;
  value: any;
};

const annoKvs = ref<ListRow[]>([]);
const labelKvs = ref<ListRow[]>([]);
const selectorKvs = ref<ListRow[]>([]);

type EditGroupType = "annotations" | "labels" | "selectors" | "none";
type EditEffectType = "single" | "batch";
const uiState = reactive({
  showOption: false,
  type: "none" as EditGroupType,
  dialogEditVisible: false,
  labelViewKey: "labels" as any,
  annotationViewKey: "annotations" as any,
  selectorViewKey: "selectors" as any
});

const dataList = computed<ListRow[]>(() => {
  switch (uiState.type) {
    case "annotations":
      return annoKvs;
    case "labels":
      return labelKvs;
    case "selectors":
      return selectorKvs;
    default:
      return [] as any;
  }
});

const editTypeOptions = [
  {
    label: t("business.workload.edit") + " metadata.labels",
    value: "single"
  },
  {
    label:
      t("business.workload.edit") +
      " metadata.labels / spec.selector.matchLabels / spec.template.metadata.labels",
    value: "batch"
  }
];

const onEditTypeChange = (val: EditEffectType) => {
  if (val === editType.value) return;
  editType.value = val;
  const isSingle = val === "single";

  uiState.type = isSingle ? "labels" : "selectors";
};

const onShouldEditGroup = (groupType: EditGroupType) => {
  uiState.type = groupType;
  uiState.dialogEditVisible = true;
  switch (groupType) {
    case "annotations":
      uiState.showOption = false;
      break;
    case "labels":
      uiState.showOption = true;
      editType.value = "single";
      break;
    case "selectors":
      uiState.showOption = true;
      editType.value = "batch";
      break;
  }
};

// 不可编辑条件
const rowOperatorDisable = (row: ListRow) => {
  return props.readonly || row.key === InjectLabelKey.Alias;
};

// 不可删除条件
const disableDialogRowDelete = (row: ListRow) => {
  return row.key === InjectLabelKey.Alias;
};

// 同步到model
const syncToModel = () => {
  const labelObj = mergeListToObject(labelKvs.value);
  const annoObj = mergeListToObject(annoKvs.value);
  const selectorObj = mergeListToObject(selectorKvs.value);

  if (metadata.value) {
    metadata.value.labels = labelObj;
    metadata.value.annotations = annoObj;
  }

  if (selector.value) {
    selector.value.matchLabels = selectorObj;
  }
};

// 重载数据列表
const reloadDataList = () => {
  annoKvs.value = objectToList(metadata.value.annotations ?? {}) as any;
  uiState.annotationViewKey = `${new Date().getTime()}`;

  labelKvs.value = objectToList(metadata.value.labels ?? {}) as any;
  uiState.labelViewKey = `${new Date().getTime()}`;

  selectorKvs.value = objectToList(selector.value?.matchLabels ?? {}) as any;
  uiState.selectorViewKey = `${new Date().getTime()}`;
};

// 新增一行
const onHandleAddRow = (group: ListRow[]) => {
  group?.push({ key: "", value: "" });
};

// 删除一行
const onHandleDeleteRow = (group: ListRow[], row: ListRow) => {
  // group?.splice(index, 1);
  const index = group.findIndex(item => item.key === row.key);
  if (index > -1) {
    group.splice(index, 1);
  }
};

const addAnnotation = () => {
  if (!metadata.value.annotations) {
    metadata.value.annotations = {};
  }

  metadata.value.annotations[""] = "";
};

const addLabel = () => {
  if (!metadata.value.labels) {
    metadata.value.labels = {};
  }

  metadata.value.labels[""] = "";
};

const addSelector = () => {
  if (!selector.value?.matchLabels) {
    selector.value.matchLabels = {};
  }

  selector.value.matchLabels[""] = "";
};

watch(
  () => metadata.value.name,
  nn => {
    setObjectFromKeys(metadata.value, ["labels", InjectLabelKey.AppName], nn);
    setObjectFromKeys(
      selector.value,
      ["matchLabels", InjectLabelKey.AppName],
      nn
    );
    reloadDataList();
  },
  { deep: true }
);

onMounted(() => {
  reloadDataList();
});
</script>

<style scoped lang="scss">
.kv-root-wrapper {
  width: 100%;

  :deep(.el-form-item__label) {
    width: 100%;
    display: flex;
  }
}
</style>
